package com.wxs.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wxs.common.dao.ResourceMapper;
import com.wxs.common.pojo.Resource;
import com.wxs.common.service.ResourceService;

/**
 * 菜单权限
 * 
 * @author admin
 *
 */
@Service
public class ResourceServiceImpl implements ResourceService {
	@Autowired
	private ResourceMapper resourceMapper;

	@Override
	public List<Resource> queryForList(Integer roleGroupId) {
		return resourceMapper.listResourceByGroupid(roleGroupId);
	}

	@Override
	public List<Resource> listAll() {
		return resourceMapper.list();
	}

	public List<Resource> treeList() {
		List<Resource> resources = resourceMapper.list();
		List<Resource> topResourceList = new ArrayList<Resource>();
		for (Resource resource : resources) {
			if (resource.getPid().compareTo(0) == 0) {
				List<Resource> children = getChildren(resources, resource.getId());
				resource.setChildren(children);
				topResourceList.add(resource);
			}
		}

		return topResourceList;
	}

	private List<Resource> getChildren(List<Resource> resourceList, Integer parentid) {
		List<Resource> children = new ArrayList<Resource>();
		for (Resource vo : resourceList) {
			if (vo.getPid().compareTo(parentid) == 0) {
				vo.setChildren(this.getChildren(resourceList, vo.getId()));
				children.add(vo);
			}
		}
		return children;
	}

	@Override
	public int saveResource(Resource resource) {
		return resourceMapper.insertSelective(resource);
	}

	@Override
	public int editResource(Resource resource) {
		return resourceMapper.updateByPrimaryKeyWithBLOBs(resource);
	}

	@Override
	public Boolean checkName(String name, Integer id) {
		Resource r = resourceMapper.selectByName(name);
		if (r == null) {
			return false;
		} else {
			if (id == null) {
				return true;
			} else if (r.getId().equals(id)) {
				return false;
			} else {
				return true;
			}
		}
	}

	@Override
	public Resource findById(Integer id) {
		return resourceMapper.selectByPrimaryKey(id);
	}

	@Override
	public void deleteById(Integer id) {
		Resource r = resourceMapper.selectByPrimaryKey(id);
		delete(r);
	}

	private void delete(Resource r) {
		if (r.getHasChildren()) {
			for (Resource r1 : r.getChildren()) {
				if (r1.getHasChildren()) {
					delete(r1);
				}
				resourceMapper.deleteRole_Resource(r1.getId());
				resourceMapper.deleteResource(r1.getId());
			}
		}
		resourceMapper.deleteRole_Resource(r.getId());
		resourceMapper.deleteResource(r.getId());
	}

	@Override
	public List<Resource> listAllByRoleid(Integer id) {
		return resourceMapper.listAllByRoleid(id);
	}

}
